﻿//-------------------------------------------------------------------------------------------------
// <copyright file="WondrousItemSerializer.cs" company="Anthony Adam">
// Copyright (c) Anthony Adam 2015. All rights reserved.
// </copyright>
//-------------------------------------------------------------------------------------------------
namespace SuperStarRounds.Classes.FileIO
{
  using System;
  using System.IO;
  using System.Runtime.Serialization.Formatters.Binary;

  using Models;

  /// <summary>
  /// Serializer that does the IO for the file saving and loading.
  /// </summary>
  public static class WondrousItemSerializer
  {
    /// <summary>
    /// Save content configuration.
    /// </summary>
    /// <param name="filename">Fully qualified configuration filename</param>
    /// <param name="itemToSerialize">Wondrous Item serialized for save</param>
    public static void SerializeWondrousItem(string filename, WondrousItemSerializedForSaveLoad itemToSerialize)
    {
      var stream = File.Open(filename, FileMode.Create);
      var binaryFormatter = new BinaryFormatter();
      try
      {
        binaryFormatter.Serialize(stream, itemToSerialize);
        stream.Close();
      }
      catch (Exception)
      {
        // if serialize fails, close the stream
        stream.Close();
      }
    }

    /// <summary>
    /// Load content configuration.
    /// </summary>
    /// <param name="filename">Fully qualified filename</param>
    /// <returns>Serialized wondrous item packet</returns>
    public static WondrousItemSerializedForSaveLoad DeserializeWondrousItem(string filename)
    {
      var itemDeSerialized = new WondrousItemSerializedForSaveLoad();
      if (!File.Exists(filename)) return itemDeSerialized;

      var stream = File.Open(filename, FileMode.Open);
      var binaryFormatter = new BinaryFormatter();
      try
      {
        itemDeSerialized = (WondrousItemSerializedForSaveLoad) binaryFormatter.Deserialize(stream);
      }
      catch (Exception)
      {
        // suppress serialization error and return the object even if partially filled
      }
      finally
      {
        stream.Close();
      }

      return itemDeSerialized;
    }
  }
}
